﻿using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using StockUtil;

namespace StockLib.Data
{
    public class CodeFileLoader
    {
        /// <summary>
        /// 载入代码表
        /// </summary>
        public virtual void Load()
        {
            //Trace.WriteLine("StockCodeLoader.Load");
            foreach (StockMarket market in StockProfile.Markets)
            {
                Load(market);
            }
        }

        /// <summary>
        /// 载入特定市场代码表
        /// </summary>
        /// <param name="market">市场类型</param>
        private void Load(StockMarket market)
        {
            FileInfo fi = new FileInfo(StockData.Instance.GetFileName(market, DataType.Code));
            if (!fi.Exists)
                return;

            FileStream fs = null;
            int packSize = Marshal.SizeOf(typeof(CodeFilePack));
            byte[] buffer = new byte[packSize * 100];
            try
            {
                fs = new FileStream(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);

                int byteNumber = 0;
                while ((byteNumber = fs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    for (int i = 0; i < byteNumber / packSize; i++)
                    {
                        CodeFilePack pack = (CodeFilePack)StructHelper.FromBytes(buffer, i * packSize, typeof(CodeFilePack));
                        Stock stock = CodeFilePack.ToInternal(ref pack);
                        if (StockContainer.Instance.ContainsKey(stock.CodeKey))
                        {
                            StockContainer.Instance.Remove(stock.CodeKey);
                        }
                        StockContainer.Instance.Add(stock.CodeKey, stock);
                    }
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
    }
}
